<template>
  <div>
    <div v-if="propData.showLine" class="line-style">
      <div v-for="item in fileList" :key="item" @click="downloadFile(item)">
        {{ item[propData.name] }}
      </div>
    </div>
    <div v-else class="history">
      <template v-if="propData.ifCard">
        <div
          style="
            display: flex;
            flex-flow: row;
            flex-wrap: wrap;
            gap: 10px;
            padding: 10px;
          "
        >
          <div
            v-for="(item, index) in fileList"
            :key="item.id"
            style="box-shadow: 0 0 10px rgb(0 0 0 / 20%)"
          >
            <div
              v-if="fileCategory(item[propData.name]) == 'image'"
              style="position: relative"
            >
              <el-image
                style="width: 150px; height: 150px"
                fit="contain"
                :src="item['imagePreviewPath']"
                :preview-src-list="srcList"
                :initial-index="index"
              />
              <el-icon
                v-if="propData.ifEdit"
                @click.stop="handleRemove(item, index)"
                style="
                  position: absolute;
                  top: 0;
                  right: 0;
                  font-size: 22px;
                  color: red;
                "
                ><CircleCloseFilled
              /></el-icon>
            </div>
            <div
              v-else
              style="
                position: relative;
                width: 150px;
                height: 150px;
                padding-top: 20px;
                text-align: center;
              "
            >
              <i
                class="uploader-file-icon"
                :icon="fileCategory(item[propData.name])"
              ></i>
              <el-tooltip content="点击预览下载文件">
                <span
                  style="
                    display: inline-block;
                    width: 130px;
                    margin-top: 20px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    word-wrap: break-word;
                    white-space: nowrap;
                    cursor: pointer;
                  "
                  @click.stop="previewFile(item)"
                >
                  {{ item[propData.name] }}</span
                >
              </el-tooltip>
              <el-icon
                v-if="propData.ifEdit"
                @click.stop="handleRemove(item, index)"
                style="
                  position: absolute;
                  top: 0;
                  right: 0;
                  font-size: 22px;
                  color: red;
                "
                ><CircleCloseFilled
              /></el-icon>
            </div>
            <div v-if="isShowUploadTime" class="upload-time">
              <p>上传人：{{ item.createUserName }}</p>
              <p>上传时间：{{ item.createTime }}</p>
            </div>
          </div>
        </div>
      </template>
      <template v-else>
        <div
          v-for="(item, index) in fileList"
          :key="item"
          class="uploader-file"
        >
          <div class="uploader-file-info">
            <div class="uploader-file-name">
              <i
                class="uploader-file-icon"
                :icon="fileCategory(item[propData.name])"
              ></i>
              {{ item[propData.name] }}
            </div>
            <div class="uploader-file-size"></div>
            <!-- 预览下载 -->
            <div class="uploader-file-status">
              <span
                class="preview"
                style="margin-right: 12px"
                @click.stop="
                  handlePreview(
                    item.url || item.downloadUrl || item[props.propData.url]
                  )
                "
                v-if="
                  isPreview(
                    item.url || item.downloadUrl || item[props.propData.url]
                  )
                "
              >
                预览
              </span>
              <span
                class="preview"
                @click.stop="
                  handleDownload(
                    item.url || item.downloadUrl || item[props.propData.url],
                    item[props.propData.name]
                  )
                "
              >
                下载
              </span>
            </div>
            <div v-if="propData.ifEdit" class="uploader-file-actions">
              <span
                class="uploader-file-remove"
                @click.stop="handleRemove(item, index)"
              ></span>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useVModel } from "@vueuse/core";
import {
  isPreview,
  handleView,
  handlePreview,
  handleDownload,
} from "@/utils/uploader";
import { getBlob } from "@/api/uploader";
interface InterfaceProps {
  isShowUploadTime?: boolean;
  cloneFile: Array<any>;
  propData: {
    name: string;
    url: string;
    ifEdit?: boolean;
    showLine?: boolean;
    ifCard?: boolean;
  };
}
/**
 * cloneFile  文件回显列表
 * propData   属性配置
 *   name     文件名称
 *   url      文件路径
 *   ifEdit   是否编辑（删除操作）
 *   showLine 是否显示线条（样式）
 */
const props = withDefaults(defineProps<InterfaceProps>(), {
  isShowUploadTime: false,
  cloneFile: () => [],
  propData: () => {
    return {
      name: "name",
      url: "url",
      ifEdit: false,
      showLine: true,
      ifCard: false,
    };
  },
});
const srcList = ref([]);
// let fileList = ref([]);

const emit = defineEmits(["update:cloneFile", "handle-remove"]);
const fileList = useVModel(props, "cloneFile", emit);
/**
 *
 * @param file 文件对象
 * @param index 对应的下标
 */
const handleRemove = (file, index: number) => {
  fileList.value.splice(index, 1);
  emit("handle-remove", { file, index });
};
//下载或者预览文件的方法
const downloadFile = (item) => {
  handleView(
    item.url || item.downloadUrl || item[props.propData.url],
    item[props.propData.name]
  );
};
const previewFile = (item) => {
  let fileType = fileCategory(item[props.propData.name]);
  if (fileType == "audio" || fileType == "video") {
    handleDownload(
      item.url || item.downloadUrl || item[props.propData.url],
      item[props.propData.name]
    );
  } else {
    handlePreview(item.url || item.downloadUrl || item[props.propData.url]);
  }
};
// file-icon
/**
 *
 * @param name 文件名称
 * @return type 文件类型
 */
const fileCategory = (name: string): string => {
  let type = "unknown";
  const h = name.substring(name.lastIndexOf(".") + 1);
  const typeMap = {
    image: ["gif", "jpg", "jpeg", "png", "bmp", "webp"],
    video: ["mp4", "m3u8", "rmvb", "avi", "swf", "3gp", "mkv", "flv"],
    audio: ["mp3", "wav", "wma", "ogg", "aac", "flac"],
    document: [
      "doc",
      "txt",
      "docx",
      "pages",
      "epub",
      "pdf",
      "numbers",
      "csv",
      "xls",
      "xlsx",
      "keynote",
      "ppt",
      "pptx",
    ],
  };
  Object.keys(typeMap).forEach((_type) => {
    const extensions = typeMap[_type];
    if (extensions.indexOf(h) > -1) type = _type;
  });
  return type;
};
watch(
  () => props.cloneFile,
  (newval) => {
    if (props.propData.ifCard) {
      srcList.value = [];
      newval.forEach((item) => {
        if (fileCategory(item[props.propData.name]) == "image") {
          console.log(item);
          getBlob(
            `/ossApi${item.url || item.downloadUrl || item[props.propData.url]}`
          ).then((res) => {
            let blob = new Blob([res]);
            const blobUrl = URL.createObjectURL(blob);
            item["imagePreviewPath"] = blobUrl;
            srcList.value.push(blobUrl);
          });
        }
      });
    }
  },
  {
    immediate: true,
  }
);
</script>

<style src="@/Uploader/components/file.scss" scoped></style>
<style lang="scss" scoped>
.history {
  min-width: 20rem;
}

.upload-time {
  padding: 8px;
  font-size: 14px;
}
</style>
